package com.lc.projects.years.hobbies;

import java.math.BigInteger;

/**
 * 1 输入一个正整数n，求n！(即阶乘)末尾有多少个0？ 比如:：n = 10； n! = 3628800，所以答案为2
 * 输入描述:
 * 输入为一行，n(1 ≤ n ≤ 1000)
 * 输出描述:
 * 输出一个整数,即题目所求
 * 输入例子:
 * 10
 * 输出例子:
 * 2
 */
public class Algorithm1 {


    public static int getResult(int n) {
        int[] arr = new int[3];
        while (n > 0) {
            int index = hash(n);
            if (index != -1) {
                if (index == 0) {
                    arr[0]++;
                } else if (index == 1) {
                    arr[1] = arr[1] + getFive(n);
                } else {
                    arr[2] = arr[2] + index / 10;
                }
            }
            n--;
        }
        int result = 0;
        if (arr[0] <= arr[1]) {
            result = arr[0] + arr[2];
        } else {
            return arr[1] + arr[2];
        }
        return result;
    }

    public static int hash(int n) {
        switch (n % 10) {
            case 2:
            case 4:
            case 6:
            case 8:
                return 0;
            case 5:
                return 1;
            case 0:
                return getZero(n + "") * 10;

            default:
                return -1;
        }
    }


    public static int getFive(int n) {
        int result = 0;
        do {
            result++;
            n = n / 5;
        } while (n >= 5 && n % 5 == 0);
        return result;
    }

    public static int getZero(String str) {
        int result = 0;
        for (int i = str.length() - 1; i >= 0; i--) {
            if (str.charAt(i) == '0') {
                result++;
            } else {
                return result;
            }
        }
        return result;
    }

    public static BigInteger getFactorial(int n) {
        BigInteger b = new BigInteger(n + "");
        if (b.intValue() == 1) {
            return new BigInteger("1");
        }
        return b.multiply(getFactorial(n - 1));
    }

    public static void main(String[] args) {
        int n = 100;
        System.out.println(getFactorial(n));
        System.out.println(getResult(n));

        System.out.print(getZero(getFactorial(n).toString()));

    }
}
